package com.patmen.android.PhoneCard;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.widget.Toast;
import android.telephony.PhoneNumberUtils;
import android.telephony.TelephonyManager;

/**
 * This class defines the methods invoked when a call has been intercepted. The
 * methods provided will:
 * <ul>
 * <li>Check to see if the outgoing call matches the criteria set in the
 * preference UI
 * <li>Perform the required transformation to the number to dial, and send that
 * information to the dialer
 * </ul>
 * 
 * @author Arvind Menon
 */
public class CallListener extends BroadcastReceiver {
	/**
	 * Method that is called when a call is being made.
	 * 
	 * An android.intent.action.NEW_OUTGOING_CALL intent is broadcast before a
	 * call is made. This method is called when that broadcast is received. The
	 * AndroidManifest file contains the required receiver tags to advertise
	 * that the class be invoked when the intent is broadcast.
	 */
	public void onReceive(Context context, Intent intent) {
		// Restore preferences
		SharedPreferences settings = context.getSharedPreferences(
				PhoneCard.PREFS_NAME, 0);

		// Check to see if the PhoneCard program should be active
		boolean phoneCardActive = settings.getBoolean("PhoneCardActive", false);
		if (!phoneCardActive) // Not active. Exit out
			return;

		// Get the number of profiles available
		int numProfiles = settings.getInt("NumProfiles", 0);

		// Fill in dummy Profile for testing
		if (numProfiles == 0) {
			numProfiles = 2;
			SharedPreferences.Editor editor = settings.edit();
			editor.putInt("NumProfiles", numProfiles);
			editor.putBoolean("Profile0Active", true);
			editor.putString("Profile0CallTo", "+91");
			editor.putString("Profile0Name", "India Call");
			editor.putString("Profile0CallPrefix", "630-621-9337");
			editor.putInt("Profile0PrefixOption", 4);
			editor.putBoolean("Profile1Active", true);
			editor.putString("Profile1CallTo", "+");
			editor.putString("Profile1Name", "International Call");
			editor.putString("Profile1CallPrefix", "630-621-9337");
			editor.putInt("Profile1PrefixOption", 4);
			editor.commit();
		}

		// Read the outgoing number
		CharSequence outGoingNumber = intent
				.getCharSequenceExtra(android.content.Intent.EXTRA_PHONE_NUMBER);

		// Make sure this is not the voicemail number
		TelephonyManager vmNumber = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		if (outGoingNumber.toString().startsWith(vmNumber.getVoiceMailNumber()))
			return;

		// Go through each saved profile
		for (int i = 0; i < numProfiles; ++i) {
			// Check to see if this profile is active
			if (!settings.getBoolean("Profile" + i + "Active", false))
				continue;

			// Extract the profile's CallTo number
			String callTo = settings.getString("Profile" + i + "CallTo",
					"PhoneCard");
			if ((outGoingNumber.toString()).startsWith(callTo)) {
				// This number matches a profile's 'CallTo' number
				// Retrieve the Profile settings
				String profileName = settings.getString("Profile" + i + "Name",
						"PhoneCard");
				String callPrefix = settings.getString("Profile" + i
						+ "CallPrefix", "");
				int prefixOption = settings.getInt("Profile" + i
						+ "PrefixOption", 0);

				// Determine the prefixOptionStr
				String prefixOptionStr = new String();
				if (prefixOption == -1) // WAIT Option
					prefixOptionStr += PhoneNumberUtils.WAIT;
				else { // PAUSE
					// Each pause is 3 seconds, add the nearest
					// number of pause characters
					for (int j = 0; j < Math.ceil((double) prefixOption / 3.0); ++j)
						prefixOptionStr += PhoneNumberUtils.PAUSE;
				}

				// Fill in the number with the required additions
				this.setResultData(PhoneNumberUtils.formatNumber(callPrefix
						+ prefixOptionStr + outGoingNumber.toString()));// .replace("+",
				// "")));

				// Display popup to inform user of modified number
				Toast.makeText(
						context,
						"PhoneCard detected a "
								+ profileName
								+ " call to "
								+ outGoingNumber
								+ ". Adding call prefix "
								+ PhoneNumberUtils.formatNumber(callPrefix
										+ prefixOptionStr), Toast.LENGTH_LONG)
						.show();

				break;
			}
		}
	}
}
